#pragma once
#include <signal.h>
#include <functional>
#include <vector>
#include "Log.hpp"
#include "Sock.hpp"

using namespace std;

class HttpServer
{
public:
    using func_t = function<void(int)>;

public:
    HttpServer(uint16_t port = 8080) : _port(port)
    {
        _listensock = sock.Socket();
        sock.Bind(_listensock, port);
        sock.Listen(_listensock);
    }
    void BindService(func_t func)
    {
        _funcs.push_back(func);
    }
    void Excute(int sock)
    {
        for (auto &iter : _funcs)
        {
            iter(sock);
        }
    }
    void Start()
    {
        signal(SIGCHLD, SIG_IGN);
        while (true)
        {
            string cli_ip;
            uint16_t cli_port;
            int serversock = sock.Accept(_listensock, &cli_ip, &cli_port);
            if (serversock < 0)
                continue;
            cout << "new connect:[" << cli_ip << "]:" << cli_port << endl;
            // 获取到连接
            // 多进程
            if (fork() == 0)
            {
                close(_listensock);
                // HandlerHttpRequest();
                Excute(serversock);
                exit(0);
            }
            close(serversock);
        }
    }
    ~HttpServer() {}

private:
    int _listensock;
    uint16_t _port;
    vector<func_t> _funcs;
    Sock sock;
};